﻿using System;
using System.Collections.Generic;
using System.Text;

namespace WAD.DAL
{
    public class DAOPush : DAO
    {
        /// <summary>
        /// 添加或更新一条记录
        /// </summary>
        /// <param name="user_id">会员ID</param>
        /// <param name="clientid">手机系统(1 安卓，2苹果)</param>
        /// <param name="userid">手机标识</param>
        /// <param name="channelid">手机推送标识</param>
        public static int AddOrUpdate(int user_id, int clientid, string userid, string channelid, int store)
        {
            //更新现有的行
            int count = 0;
            if (clientid == 2)
                count = ExecuteNonQuery(string.Format("update [push] set user_id={0},userid='{1}',channelid='{2}',clientid={3},state={4},store={5},date=getdate() where user_id={0} or channelid='{2}'", user_id, userid, channelid, clientid, 1, store));
            else
                count = ExecuteNonQuery(string.Format("update [push] set user_id={0},userid='{1}',channelid='{2}',clientid={3},state={4},store=null,date=getdate() where user_id={0} or channelid='{2}'", user_id, userid, channelid, clientid, 1));
            //若存在多条记录，删除只保留1条
            if (count > 1)
            {
                ExecuteNonQuery(string.Format("delete push where [user_id]={0} and id not in (select top 1 t2.id from push t2 where user_id={0})", user_id));
            }
            else if (count < 1)
            {   //添加新行
                if (clientid == 2)
                    count = ExecuteNonQuery(string.Format("insert into [push] (user_id,userid,channelid,clientid,state,store,date)values({0},'{1}','{2}','{3}',{4},{5},getdate())", user_id, userid, channelid, clientid, 1, store));
                else
                    count = ExecuteNonQuery(string.Format("insert into [push] (user_id,userid,channelid,clientid,state,store,date)values({0},'{1}','{2}','{3}',{4},null,getdate())", user_id, userid, channelid, clientid, 1));
            }
            return count;
        }

        public static List<Dictionary<string, object>> GetPushList(string sql)
        {
            return GetList(sql);
        }
    }
}